/**
 * 
 */
package com.es.disped.web.controller.sms;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.es.disped.api.sms.SmsService;
import com.es.disped.common.constant.AliSms;
import com.es.disped.common.model.MsgModel;
import com.es.disped.core.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @author Anson<br>
 *
 * Copyright by EasyShare 2019<br>
 *
 * All right reserved<br>
 *
 * Created on 下午4:06:29<br>
 *
 * 名称：SmsController.java<br>
 *
 * 描述：<br>
 */
@Api("短信发送")
@Controller
@RequestMapping("/sms")
public class SmsController extends BaseController{

	@Autowired
	SmsService smsService;
	@Autowired
	RedisTemplate<String, String> redisTemplate; 
	
//	@RequestMapping(value="/templatecode/list",method=RequestMethod.POST)
//	public @ResponseBody MsgModel getTemplateCodeList()
//	{
//		Map<Integer, String> tempalteCodeMap=new HashMap<Integer, String>();
//		for(AliSms.ALI_MESSAGE_TEMPLATE_CODE templateCode:AliSms.ALI_MESSAGE_TEMPLATE_CODE.values())
//		{
//			tempalteCodeMap.put(templateCode.getName(), templateCode.getValue());
//		}
//		return new MsgModel(HttpStatus.OK.value(), "短信模板获取成功",tempalteCodeMap);
//	}
		
	
	
	/**
	 * 手机号认证-验证码请求
	 * 
	 * @param paramMap
	 * 		{@link Map} 请求参数-phone
	 * @return
	 * 		{@link MsgModel} 消息返回对象
	 */
	@ApiOperation(value="短信验证码发送",response=MsgModel.class,httpMethod="POST",notes="发送短信验证码")
	@ApiImplicitParam(name="phone",value="手机号",required=true,dataType="String")
	@RequestMapping(value="/send/code",method=RequestMethod.POST)
	public @ResponseBody MsgModel sendVertifyCode(@RequestBody Map<String, Object> paramMap)
	{
		String vertifyCode=String.valueOf((int)((Math.random()*9+1)*1000000));
		String templateCode=AliSms.ALI_MESSAGE_TEMPLATE_CODE.VERTIFY_CODE.getValue(); 
		String phone=paramMap.get("phone").toString();
		JSONObject paramJson= new JSONObject();
		paramJson.put("code", vertifyCode);
		MsgModel msgModel=smsService.sendMessage(AliSms.ALI_MESSAGE_SIGN_NAME.ES_TECH.getValue(), phone,
				templateCode, paramJson.toJSONString());
		if(msgModel.getStatus()==HttpStatus.OK.value()&&msgModel.getMsg().equals("OK"))
		{
			redisTemplate.opsForValue().set(phone, vertifyCode,30,TimeUnit.MINUTES); 
		}
		return new MsgModel((msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value()
				, (msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?"验证码发送成功":msgModel.getMsg());
	}
	
	
	/**
	 * 验证码校验
	 * @param paramMap
	 * 		phone-value手机号<br>
	 * 		code-value验证码
	 * @return
	 * 		{@link MsgModel}
	 */
    @ApiOperation(value="验证短信验证码",httpMethod="POST",response=MsgModel.class,notes="验证短信验证码是否正确")
    @ApiImplicitParams({
    	@ApiImplicitParam(name="phone", value="用户手机号",required=true,dataType="String"),
    	@ApiImplicitParam(name="code", value="验证码",required=true,dataType="String")
    })
    @RequestMapping(value="/vertify/code",method=RequestMethod.POST)
    public @ResponseBody MsgModel vertify(@RequestBody Map<String, Object> paramMap)
    {
    	String phone=paramMap.get("phone").toString();
    	String code=paramMap.get("code").toString();
    	String redisCode=redisTemplate.opsForValue().get(phone);
    	return new MsgModel(redisCode.equals(code)?HttpStatus.OK.value():HttpStatus.NOT_FOUND.value(),
    			redisCode.equals(code)?"":"验证失败");
    }
	
    /**
     * 一对一短信发送
     * @param paramMap
     * 		phone-value手机号<br>
     * 		paramJson-value("content":"value")参数内容，JSON格式
     * @return
     * 		{@link MsgModel}
     */
	@ApiOperation(value="一对一发送短信",response=MsgModel.class,httpMethod="POST",
			notes="一对一短信发送，提交参数中，paramJson变量值为JSON对象->content:value")
	@ApiImplicitParams({
		@ApiImplicitParam(name="phone",value="手机号",required=true,dataType="String",example="{phone:'11111111111',paramJson:'{'content':'新消息'}'}"),
		@ApiImplicitParam(name="paramJson",value="短信内容的JSON字符串{'content':'XXX'},content名称不可变",required=true,dataType="String")
	})
	@RequestMapping(value="/send/notice",method=RequestMethod.POST)
	public @ResponseBody MsgModel sendMessage(@RequestBody Map<String, Object> paramMap)
	{
		String phone=paramMap.get("phone").toString();
		String paramJson=paramMap.get("paramJson").toString();
		MsgModel msgModel=smsService.sendMessage(AliSms.ALI_MESSAGE_SIGN_NAME.ES_TECH.getValue(),
				phone, AliSms.ALI_MESSAGE_TEMPLATE_CODE.ORDINARY_NOTICE.getValue(), paramJson);
		return new MsgModel((msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value()
				, (msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?"通知发送成功":msgModel.getMsg());
	}
	
	
	/**
	 * 群发短信
	 * @param paramMap
	 * 		phone-value的JSON数组，名为phoneJsonArray<br>
	 * 		content-value的的json对象，名为paramJson
	 * @return
	 * 		{@link MsgModel}
	 */
	@ApiOperation(value="群发短信",response=MsgModel.class,httpMethod="POST",
			notes="短信群发，提交参数中，paramJson变量值为JSON对象->content:value")
	@ApiImplicitParams({
		@ApiImplicitParam(name="phoneJsonArray",value="phonjson数组",required=true,dataType="String"),
		@ApiImplicitParam(name="paramJson",value="json字符串{'content':'XXX'}",required=true,dataType="String")
	})
	@RequestMapping(value="/send/batch",method=RequestMethod.POST)
	public @ResponseBody MsgModel sendBatch(@RequestBody Map<String, Object> paramMap)
	{
		JSONArray phoneJsonArray=(JSONArray) paramMap.get("phoneJsonArray");
		JSONArray signNameJsonArray= new JSONArray();
		JSONArray paramJsonArray=new JSONArray();
		for(int i=0;i<phoneJsonArray.size();i++)
		{
			signNameJsonArray.add(AliSms.ALI_MESSAGE_SIGN_NAME.ES_TECH.getValue());
			JSONObject jsonObject=(JSONObject) paramMap.get("paramJson");
			paramJsonArray.add(jsonObject);
		}
		MsgModel msgModel=smsService.sendMessages(
				signNameJsonArray.toJSONString(),
				phoneJsonArray.toJSONString(),
				AliSms.ALI_MESSAGE_TEMPLATE_CODE.ORDINARY_NOTICE.getValue(),
				paramJsonArray.toJSONString());
		return new MsgModel((msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value()
				, (msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?"通知发送成功":msgModel.getMsg());
	}
	
	
	/**
	 * 短信查询接口
	 * @param paramMap
	 * 		{@link HashMap}<br>
	 * 		phone-value;sendDate-value;offset-value;limit-value
	 * @return
	 * 		{@link MsgModel}
	 */
	@ApiOperation(value="短信查询接口",response=MsgModel.class,httpMethod="POST",
			notes="查询已发送的短信，手机号，发送日期，当前查询页，每页数据容量")
	@ApiImplicitParams({
		@ApiImplicitParam(name="phone",value="手机号",required=true,dataType="String"),
		@ApiImplicitParam(name="sendDate",value="发送日期",required=true,dataType="String"),
		@ApiImplicitParam(name="offset",value="查询位置",required=true,dataType="Integer"),
		@ApiImplicitParam(name="limit",value="查询数量",	required=true,dataType="Integer")
	})
	@RequestMapping(value="/query",method=RequestMethod.POST)
	public @ResponseBody MsgModel query(@RequestBody Map<String, Object> paramMap)
	{
		MsgModel msgModel=null;
		if(Optional.of(paramMap)
				.filter(phone->paramMap.get("phone")!=null)
				.filter(sendDate->paramMap.get("sendDate")!=null)
				.filter(currentPage->paramMap.get("offset")!=null)
				.filter(pageSize->paramMap.get("limit")!=null)
				.isPresent())
		{
			msgModel=smsService.queryMessage(
					  paramMap.get("phone").toString(),
					  paramMap.get("sendDate").toString(),
					  Long.valueOf(paramMap.get("offset").toString()),
					  Long.valueOf(paramMap.get("limit").toString()));
		}

		return new MsgModel((msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value()
				, (msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?"":msgModel.getMsg()
				, (msgModel.getStatus()==HttpStatus.OK.value()
				&&msgModel.getMsg().equals("OK"))?msgModel.getRes():"");
	}
}
